﻿package net.wangit.framework.exception;

import java.io.PrintStream;
import java.io.PrintWriter;

@SuppressWarnings("serial")
public abstract class NestableException extends Exception {
	private Throwable cause;

	public NestableException(String s) {
		super(s);
	}

	public NestableException(String s, Throwable cause) {
		super(s);
		this.cause = cause;
	}

	public Throwable getCause() {
		return cause != this ? cause : null;
	}

	public void printStackTrace(PrintStream ps) {
		super.printStackTrace(ps);
		if (cause != null && cause != this) {
			ps.println("    with nested exception:");
			cause.printStackTrace(ps);
		}
	}

	public void printStackTrace(PrintWriter pw) {
		super.printStackTrace(pw);
		if (cause != null && cause != this) {
			pw.println("    with nested exception:");
			cause.printStackTrace(pw);
		}
	}

	public String getMessage() {
		if (cause == null || cause == this)
			return super.getMessage();
		else
			return (new StringBuilder(String.valueOf(super.getMessage())))
					.append("\n    with nested exception:\n ").append(
							cause.getMessage()).toString();
	}
}
